
//使用lowdb来本地化存储数据
const dbPtah="./api_server/store/lowdb/"
const low=require('lowdb');
const FileSync=require('lowdb/adapters/FileSync');  // 有多种适配器可选择
const lodashId = require('lodash-id')

class BaseService {

  //父类构造函数  创建对应的db
  constructor(tableName){
    this.tableName=tableName;
    let  adapter=new FileSync(dbPtah+`/${tableName}.json`)  // 申明一个适配器
    this.db=low(adapter)
    this.db._.mixin(lodashId)
    if(!this.db.has(this.tableName).value()){
      this.db.set(this.tableName, []).write()
    }
    this.get=this.db.get(this.tableName)
  }

  /*
  * 查询一条
  * */
  one(id){
    return  this.get.getById(id).value()
  }

  /*
  * 分页查询
  * 起始页start  条数limit
  * 排序sorter [ {'column':'id','order':'desc'} ]
  * 模糊查询queryParam  [ {'key':'value'} ]
  **/
  list(page){
    let list=this.get
    let total=list.size().value()
    //模糊查询
    if(page.queryParam){
      for (let key in page.queryParam){
        list.filter(e=>{
          return  e[key].match(page.queryParam['key'])
        })
      }
    }
    //排序
    if(!page.sorter){
      list.orderBy('id','desc')
    }else {
      page.sorter.forEach(e=>{
        list.orderBy(e.column,e.order)
      })
    }
    //分页
    let res=list.cloneDeep().value()
    res=res.slice(page.start?page.start:0,(page.limit?(page.limit===-1?total:page.limit):10))
    page['total']=total
    page['list']=res
    return page
  }

  /*
  * 更新一条
  **/
  update(example){
    //有id就更新  否则插入
    if(example.id){
      this.get.upsert(example).write()
    }else {
        let all=this.list({limit:-1})['list'];
        let id=all.length==0?1:Number(all[0]['id'])+1
        example['id']=id
        all.unshift(example)
        this.db.set(this.tableName, all).write()
    }
  }

  /*
  * 删除一条
  **/
  delete(id){
    this.get.removeById(id).write()
  }
}

export default BaseService;
